#include "crow.h"
#include "crow/middlewares/cors.h"
#include <sqlite3.h>
#include <iostream>
#include <string>

// 增加地点热度的函数
double increasePopularity(int placeId) {
    sqlite3 *db;
    char *errMsg = 0;
    int rc;
    double newPopularity = 0;
    
    // 打开数据库
    rc = sqlite3_open("tour_system.db", &db);
    if (rc) {
        std::cerr << "无法打开数据库: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return -1;
    }
    
    // 第一步：获取当前热度
    std::string selectSql = "SELECT popularity FROM places WHERE id = " + std::to_string(placeId);
    sqlite3_stmt *stmt;
    
    rc = sqlite3_prepare_v2(db, selectSql.c_str(), -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        std::cerr << "SQL准备错误: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return -1;
    }
    
    if (sqlite3_step(stmt) == SQLITE_ROW) {
        double currentPopularity = sqlite3_column_double(stmt, 0);
        newPopularity = currentPopularity + 0.5;
    } else {
        std::cerr << "未找到ID为" << placeId << "的地点" << std::endl;
        sqlite3_finalize(stmt);
        sqlite3_close(db);
        return -1;
    }
    
    sqlite3_finalize(stmt);
    
    // 第二步：更新热度（+0.5）
    std::string updateSql = "UPDATE places SET popularity = " + std::to_string(newPopularity) + 
                          " WHERE id = " + std::to_string(placeId);
    
    rc = sqlite3_exec(db, updateSql.c_str(), 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        std::cerr << "SQL错误: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        sqlite3_close(db);
        return -1;
    }
    
    // 关闭数据库
    sqlite3_close(db);
    return newPopularity;
}

// 示例：如何在Crow应用中添加这个API端点
void setupPopularityAPI(crow::App<crow::CORSHandler>& app) {
    CROW_ROUTE(app, "/api/increase_popularity/<int>").methods(crow::HTTPMethod::POST)
    ([](const crow::request& req, int placeId) {
        double newPopularity = increasePopularity(placeId);
        
        if (newPopularity < 0) {
            return crow::response(500, "{\"error\": \"增加热度失败\"}");
        }
        
        // 返回新的热度值
        std::string responseBody = "{\"success\": true, \"place_id\": " + std::to_string(placeId) + 
                                 ", \"new_popularity\": " + std::to_string(newPopularity) + "}";
        return crow::response(200, responseBody);
    });
}

/*
// 在您的主应用中这样使用：
int main() {
    crow::App<crow::CORSHandler> app;
    
    // 设置CORS
    auto& cors = app.get_middleware<crow::CORSHandler>();
    cors
      .global()
      .headers("X-Requested-With", "Content-Type", "Accept")
      .methods("POST", "GET", "PUT", "DELETE")
      .origin("*");
      
    // 设置API端点
    setupPopularityAPI(app);
    
    // 其他路由设置...
    
    // 启动服务器
    app.port(3000).multithreaded().run();
    
    return 0;
}
*/ 